package com.stx.jeepay.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stx.jeepay.core.dao.MchInfoDao;
import com.stx.jeepay.core.entity.*;

import com.stx.jeepay.core.enums.ApiCodeEnum;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


@Service("mchInfoService")
public class MchInfoServiceImpl extends ServiceImpl<MchInfoDao, MchInfoEntity> implements MchInfoService {

    @Autowired
    private IsvInfoService isvInfoService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MchAppService mchAppService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private MchPayPassageService mchPayPassageService;

    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;

    @Autowired
    private SysUserAuthService sysUserAuthService;

    /**
     * 添加商户
     *
     * @param mchInfo
     * @param loginUserName
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addMch(MchInfoEntity mchInfo, String loginUserName) {
        // 校验特邀商户信息
        if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB && StringUtils.isNotEmpty(mchInfo.getIsvNo())) {
            // 当前服务商状态是否正确
            IsvInfoEntity isvInfo = isvInfoService.getById(mchInfo.getIsvNo());
            if (isvInfo == null || isvInfo.getState() == CS.NO) {
                throw new BizException("当前服务商不可用");
            }
        }
        // 插入商户基本信息
        boolean saveResult = save(mchInfo);
        if (!saveResult) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
        // 插入用户信息
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setLoginUsername(loginUserName);
        sysUser.setRealname(mchInfo.getContactName());
        sysUser.setTelphone(mchInfo.getContactTel());
        sysUser.setUserNo(mchInfo.getMchNo());
        sysUser.setBelongInfoId(mchInfo.getMchNo());
        sysUser.setSex(CS.SEX_MALE);
        sysUser.setIsAdmin(CS.YES);
        sysUser.setState(mchInfo.getState());
        sysUserService.addSysUser(sysUser, CS.SYS_TYPE.MCH);

        // 插入商户默认应用
        MchAppEntity mchApp = new MchAppEntity();
        mchApp.setAppId(IdUtil.objectId());
        mchApp.setMchNo(mchInfo.getMchNo());
        mchApp.setAppName("默认应用");
        mchApp.setAppSecret(RandomUtil.randomString(128));
        mchApp.setState(CS.YES);
        mchApp.setCreatedBy(sysUser.getRealname());
        mchApp.setCreatedUid(sysUser.getSysUserId());
        boolean saveMchAppResult = mchAppService.save(mchApp);
        if (!saveMchAppResult) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }

        // 存入商户默认用户ID
        MchInfoEntity updateRecord = new MchInfoEntity();
        updateRecord.setMchNo(mchInfo.getMchNo());
        updateRecord.setInitUserId(sysUser.getSysUserId());
        boolean updateResult = updateById(updateRecord);
        if (!updateResult) {
            throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
        }
    }

    /** 删除商户 **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Long> removeByMchNo(String mchNo) {
        try {
            // 0.当前商户是否存在
            MchInfoEntity mchInfo = getById(mchNo);
            if (mchInfo==null){
                throw new BizException("商户不存在");
            }
            // 1.查看当前商户是否存在交易数据
            int payCount = payOrderService.count(new LambdaQueryWrapper<PayOrderEntity>().eq(PayOrderEntity::getMchNo,mchNo));
            if (payCount>0){
                throw new BizException("该商户存在交易数据不可进行删除");
            }
            // 2.删除当前商户配置的支付通道
            mchPayPassageService.remove(new LambdaQueryWrapper<MchPayPassageEntity>().eq(MchPayPassageEntity::getMchNo,mchNo));
            // 3.删除当前商户支付接口配置参数
            List<String> appIdList = new LinkedList<>();
            mchAppService.list(new LambdaQueryWrapper<MchAppEntity>()
                    .eq(MchAppEntity::getMchNo,mchNo))
                    .stream().forEach(i->appIdList.add(i.getAppId()));
            if (CollUtil.isNotEmpty(appIdList)){
                payInterfaceConfigService.remove(new LambdaQueryWrapper<PayInterfaceConfigEntity>()
                        .in(PayInterfaceConfigEntity::getInfoId,appIdList)
                        .eq(PayInterfaceConfigEntity::getInfoType,CS.INFO_TYPE_MCH_APP));
            }

            List<SysUserEntity> userList = sysUserService.list(new LambdaQueryWrapper<SysUserEntity>()
                    .eq(SysUserEntity::getBelongInfoId, mchNo)
                    .eq(SysUserEntity::getSysType, CS.SYS_TYPE.MCH));

            // 4.删除当前商户应用信息
            if (CollUtil.isNotEmpty(appIdList)){
                mchAppService.removeByIds(appIdList);
            }

            // 返回的用户id
            List<Long> userIdList = new ArrayList<>();
            if (CollUtil.isNotEmpty(userList)){
                for (SysUserEntity user : userList) {
                    userIdList.add(user.getSysUserId());
                }
                // 5.删除当前商户用户子用户信息
                sysUserAuthService.remove(new LambdaQueryWrapper<SysUserAuthEntity>()
                        .in(SysUserAuthEntity::getUserId,userIdList));
            }
            // 6.删除当前商户的登录用户
            sysUserService.remove(new LambdaQueryWrapper<SysUserEntity>()
                    .eq(SysUserEntity::getBelongInfoId,mchNo)
                    .eq(SysUserEntity::getSysType,CS.SYS_TYPE.MCH));

            // 7.删除当前商户
            boolean removeMchInfo = removeById(mchNo);
            if (!removeMchInfo){
                throw new BizException("删除当前商户失败");
            }
            return userIdList;
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }
    }
}